package com.uwosh.cs342.g6.mapapp;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class FriendList extends ListActivity {

	// All static variables
	int FID = -1;
	int Findy = -1;
	final String URL = "http://softeng.cs.uwosh.edu/students/cs342g6/friendlistnew.php?id="
			+ Login.currentUserId; // XML node keys
	final String deleteURL = "http://softeng.cs.uwosh.edu/students/cs342g6/deleteFriend.php?id=";// XML
	final String KEY_ITEM = "message"; // parent node
	final String KEY_ID = "id";
	final String KEY_FROM = "from";
	final String KEY_TO = "to";
	final String KEY_TEXT = "text";
	final String KEY_READ = "read";

	ArrayList<HashMap<String, String>> menuItems;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		menuItems = new ArrayList<HashMap<String, String>>();

		XMLParser parser = new XMLParser();
		String xml = parser.getXmlFromUrl(URL);
		Document doc = parser.getDomElement(xml);

		NodeList nl = doc.getElementsByTagName(KEY_ITEM);
		for (int i = 0; i < nl.getLength(); i++) {
			HashMap<String, String> map = new HashMap<String, String>();
			Element e = (Element) nl.item(i);
			map.put(KEY_ID, parser.getValue(e, KEY_ID));
			map.put(KEY_FROM, "Friend: " + parser.getValue(e, KEY_FROM));
			map.put(KEY_TO, parser.getValue(e, KEY_TO));
			map.put(KEY_TEXT, parser.getValue(e, KEY_TEXT));
			map.put(KEY_READ, parser.getValue(e, KEY_READ));
			menuItems.add(map);

		}
		ListAdapter adapter = new SimpleAdapter(this, menuItems,
				R.layout.activity_friend_list, new String[] { KEY_ID, KEY_FROM,
						KEY_TEXT, KEY_TO }, new int[] { R.id.name,
						R.id.desciption });

		setListAdapter(adapter);

		// selecting single ListView item
		ListView lv = getListView();

		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// getting values from selected ListItem
				FID = Integer.parseInt(menuItems.get(position).get(KEY_ID));
				Findy = Integer.parseInt(menuItems.get(position).get(KEY_READ));
				// Starting new intent
				Intent in = new Intent(getApplicationContext(), Viewfriend.class);
				in.putExtra(KEY_ID, FID+"");
				in.putExtra(KEY_READ, Findy+"");
				startActivity(in);
			}
		});
				
		lv.setOnItemLongClickListener(new OnItemLongClickListener() {
						
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {

				// Creating alert Dialog with two Buttons
				FID = Integer.parseInt(menuItems.get(position).get(KEY_ID));
				// FID = position+" ";
				AlertDialog.Builder alertDialog = new AlertDialog.Builder(
						FriendList.this);

				// Setting Dialog Title
				alertDialog.setTitle("Confirm Delete..." + FID);

				// Setting Dialog Message
				alertDialog
						.setMessage("Are you sure you want delete this friendship?");

				// Setting Icon to Dialog
				// alertDialog.setIcon(R.drawable.delete);

				// Setting Positive "Yes" Button
				alertDialog.setPositiveButton("YES",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								// Write your code here to execute after dialog
								deletefriendship(FID);
								// Toast.makeText(getApplicationContext(),
								// "You clicked on YES",
								// Toast.LENGTH_SHORT).show();
							}
						});
				// Setting Negative "NO" Button
				alertDialog.setNegativeButton("NO",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								// Write your code here to execute after dialog
								Toast.makeText(getApplicationContext(),
										"You clicked on NO", Toast.LENGTH_SHORT)
										.show();
								dialog.cancel();
							}
						});

				// Showing Alert Message
				alertDialog.show();
				// onLongListItemClick(parent, view, position, id);

				return false;
			}
		});
	}

	private void onLongListItemClick(AdapterView<?> parent, View view,
			int position, long id) {
		// getting values from selected ListItem
		String name = ((TextView) view.findViewById(R.id.name)).getText()
				.toString();
		String description = ((TextView) view.findViewById(R.id.desciption))
				.getText().toString();

		// call alert box for delete confirmation

	}

	public void deletefriendship(int ID) {
		try {
			String x = new deleteFriendRequests().execute(ID).get();
		} catch (InterruptedException e) {
			// 
			e.printStackTrace();
		} catch (ExecutionException e) {
			// 
			e.printStackTrace();
		}
		this.finish();
	}

	public class deleteFriendRequests extends
			AsyncTask<Integer, Context, String> {

		@Override
		protected String doInBackground(Integer... params) {

			int userNum = Login.currentUserId;
			String response = "";

			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(deleteURL + params[0]);
			try {

				// Execute HTTP Post Request

				ResponseHandler<String> responseHandler = new BasicResponseHandler();
				response = httpclient.execute(httppost, responseHandler);
				response = response.trim();
				int temp = Integer.parseInt(response);
				if (temp == 1) {
					return "success";
				} else {
					return "failure";
				}
			} catch (ClientProtocolException e) {
			} catch (IOException e) {
			}
			return null;
		}

		@Override
		protected void onPostExecute(String values) {

			if (values.equals("success")) {
				Context context = getApplicationContext();
				Toast.makeText(context, "deleted", Toast.LENGTH_SHORT).show();
				
			}

		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_friend_list, menu);
		return true;
	}

}
